package pl.donajski.magisterka;

import java.util.List;
import java.util.Random;

public class RandomGenerator implements IInitialStateGenerator {

	public State getInitialState(List<Task> tasks, List<Node> nodes) {
		this.mState = new State(tasks, nodes);
		
		this.generateRandomAssignment();
		
		return this.mState;
	}
	
	private void generateRandomAssignment() {
		Random r = new Random();
		int n;
		for(Task t : this.mState.getTasks()) {
			do {
				while((n = Math.abs(r.nextInt())) < 0);
				
				n = n % this.mState.getNodes().size();
			} while(!this.mState.getNodes().get(n).canAssign() || 
					(!t.isPrimary() && 
							t.getPrimaryIndex().getAssignment().equals(this.mState.getNodes().get(n))));
			t.setAssignment(this.mState.getNodes().get(n));	
		}
		
		if(!this.mState.isValid())
			throw new RuntimeException("NOT VALID???");
		
		this.mState.setFlows();
		this.mState.calculateCost();
		
	}

	private State mState;

}
